package com.sairobo.base.common.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

public abstract class MultiUpload
{
	public static final String REQUEST = "MultiUpload_REQUEST";

	public static final String FILE = "MultiUpload_FILE";

	public static final String PATH = "MultiUpload_PATH";

	public List<?> multiUpload(HttpServletRequest request, String rootPath, Class<?> clazz, Map<String, Object> map) throws IOException, InstantiationException, IllegalAccessException
	{
		long startTime = System.currentTimeMillis();
		List<Object> result = new ArrayList<Object>();
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request))
		{
			if (null == map)
			{
				map = new HashMap<String, Object>();
			}
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			map.put(REQUEST, request);
			// 获取multiRequest 中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();
			File f = new File(rootPath);
			if (!f.exists())
			{
				f.mkdir();
			}
			while (iter.hasNext())
			{
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null)
				{
					String path = rootPath + rename(file.getOriginalFilename());
					file.transferTo(new File(path));
					map.put(FILE, file);
					map.put(PATH, path);
					Object obj = clazz.newInstance();
					wrapper(obj, map);
					result.add(obj);
				}
			}
		}

		long endTime = System.currentTimeMillis();
		System.out.println("springUpload的运行时间：" + String.valueOf(endTime - startTime) + "ms");
		return result;
	}

	protected abstract void wrapper(Object obj, Map<String, Object> map);

	/**
	 * 文件重命名
	 * 
	 * @param originalFilename
	 * @return
	 */
	protected String rename(String originalFilename)
	{
		String head = UUID.randomUUID().toString().replace("-", "");
		return head + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
	}
}
